package com.xdz.xytx.controller;

import com.xdz.xytx.common.BaseResponse;
import com.xdz.xytx.common.ErrorCode;
import com.xdz.xytx.common.ResultUtils;
import com.xdz.xytx.model.request.UploadFileRequest;
import com.xdz.xytx.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private AliOssUtil aliOssUtil;
    /**
     * 文件上传
     * @param file
     * @param
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file")MultipartFile file,HttpServletRequest request){
        log.info("文件上传：{}",file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String entension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //+UUID构造新的文件名称
            String objectName = UUID.randomUUID().toString() + entension;

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return ResultUtils.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败:{}",e);
        }
    return ResultUtils.error(ErrorCode.SYSTEM_ERROR,"文件上传失败");
}
}
